<%@ page language="java" isELIgnored="false" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="static/js/jquery.min.js"></script>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
</head>
<body>
<%--<h2>Hello World!</h2>--%>
<div>
    <h2>multipart 文件上传</h2>
<%--    <fieldset>--%>
    <div>
        <form method="post" enctype="multipart/form-data" action="/demo/upload">
            <input type="text" name="name"/>
            <input type="file" name="uploadFile"/>
            <input type="submit" value="上传"/>
        </form>
    </div>
<%--    </fieldset>--%>
    <div class="form-group">
<%--        <label for="inputPassword3" class="col-sm-2 control-label">身份证正面照片:</label>--%>
        <div class="col-sm-10">
            <input type="hidden" name="img"  id="photoUrl"/>
            <input type="file" name="uploadFile" id="uploadFile" onchange="setImg(this);">
            <span><img id="photourlShow" src="static/image/abc.png" width="300" height="197"/></span>
        </div>
    </div>
</div>
</body>

<script>
    function setImg(obj){
        var f=$(obj).val();
        alert(f);
        console.log(obj);
        if(f == null || f ==undefined || f == ''){
            return false;
        }
        if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
        {
            alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
            $(obj).val('');
            return false;
        }
        var data = new FormData();
        console.log(data);
        $.each($(obj)[0].files,function(i,file){
            data.append("uploadFile", file);
            data.append("name", "123");
        });
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/demo/upload",
            data: data,
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType:"json",
            success: function(ret) {
                console.log(ret);
                // if(ret.code==0){
                //     $("#photoUrl").val(ret.result.url);//将地址存储好
                //     $("#photourlShow").attr("src",ret.result.url);//显示图片
                //     alertOk(ret.message);
                // }else{
                //     alertError(ret.message);
                //     $("#url").val("");
                //     $(obj).val('');
                // }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("上传失败，请检查网络后重试");
            }
        });
    }

</script>
</html>
